coding = 'utf-8'
import sys, os, time, signal
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
import socket
import subprocess as sp
import webbrowser



class App(QWidget):

    info = {}

    def __init__(self):
        super().__init__()
        self.title = "看直播"
        self.left = 20
        self.top = 20
        self.width = 320
        self.height = 200
        self.initUI()


    def initUI(self):

        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)


        self.button1 = QPushButton("开启我的直播", self)

        self.button1.setToolTip("put me on video")

        self.button1.move(50, 50)

        self.button1.clicked.connect(self.on_click1)



        self.button2 = QPushButton("观看直播", self)

        self.button2.setToolTip("watch little sister")

        self.button2.move(50, 100)

        self.button2.clicked.connect(self.on_click2)



        self.button3 = QPushButton("关闭摄像头", self)

        self.button3.setToolTip("watch little sister")

        self.button3.move(50, 150)

        self.button3.clicked.connect(self.on_click3)

        self.show()



    @pyqtSlot()
    def on_click1(self):
        hostname = socket.gethostname()
        ip = socket.gethostbyname(hostname)

        # ip = "127.0.0.1"
        # ip = "10.2.0.174"
        # if nginx is None:
        #     sp.run(['nginx'])
        rtmpurl = 'rtmp://' + str(ip) + ':1935/hls/camera'
        url = 'http://' + str(ip) + ':8080/hls/camera.m3u8'

        command = ['ffmpeg',
                   '-f', 'avfoundation',
                   '-framerate', '30',
                   '-video_size',
                   '1280x720', '-i',
                   "0:0", '-vcodec',
                   'libx264', '-preset',
                   'ultrafast', '-acodec',
                   'libmp3lame', '-ar',
                   '44100', '-ac',
                   '1', '-f',
                   'flv', rtmpurl]

        pipe = sp.Popen(command, stdin=sp.PIPE)
        self.info['pipe'] = pipe
        self.info['url'] = url
        return self.info




    @pyqtSlot()
    def on_click2(self):
        # _,url = self.on_click1
        # print(url)
        webbrowser.open(self.info['url'], new=0, autoraise=True)
        webbrowser.get()
        # sp.run(['ptthon])



    @pyqtSlot()
    def on_click3(self):
        os.kill(self.info['pipe'].pid, signal.SIGKILL)
        print('xxxx3333')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())